<template>
    <div class="dataType-collapse">
        <el-collapse v-model="activeName" @change="getInitData(activeName)" accordion>
            <el-collapse-item name="house">
                <template #title>
                    <el-icon>
                        <HomeFilled />
                    </el-icon>
                    <span>房屋数据类型</span>
                </template>

                <h4>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;房屋类型</h4>
                <div class="tag-wrapper">
                    <el-tag v-for="houseType in houseTypeData" :key="houseType.id" class="ml-2" closable :hit="true"
                        :disable-transitions="false" @close="deleteHouseType(houseType.id)">
                        {{ houseType.name }}
                    </el-tag>

                    <el-input v-if="inputHouseTypeVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20"
                        size="small" @blur="createHouseType(inputValue)" />

                    <el-button v-else class="button-new-tag ml-1" size="small" @click="showHouseTypeInput">+ 添加</el-button>
                </div>

                <h4>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;房屋状态</h4>
                <div class="tag-wrapper">
                    <el-tag v-for="houseStatus in houseStatusData" :key="houseStatus.id" class="ml-2" closable :hit="true"
                        :disable-transitions="false" @close="deleteHouseStatus(houseStatus.id)">
                        {{ houseStatus.name }}
                    </el-tag>

                    <el-input v-if="inputHouseStatusVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20"
                        size="small" @blur="createHouseStatus(inputValue)" />

                    <el-button v-else class="button-new-tag ml-1" size="small" @click="showHouseStatusInput">+
                        添加</el-button>
                </div>
            </el-collapse-item>

            <el-collapse-item name="workorder">
                <template #title>
                    <el-icon>
                        <List />
                    </el-icon>
                    <span>工单数据类型</span>
                </template>
                <h4>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;工单分类</h4>
                <div class="tag-wrapper">
                    <el-tag v-for="workorderCategory in workorderCategoryData" :key="workorderCategory.id" class="ml-2"
                        closable :hit="true" :disable-transitions="false"
                        @close="deleteWorkorderCategory(workorderCategory.id)">
                        {{ workorderCategory.name }}
                    </el-tag>

                    <el-input v-if="inputWorkorderCategoryVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20"
                        size="small" @blur="createWorkorderCategory(inputValue)" />

                    <el-button v-else class="button-new-tag ml-1" size="small" @click="showWorkorderCategoryInput">+
                        添加</el-button>
                </div>

                <h4>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;工单状态</h4>
                <div class="tag-wrapper">
                    <el-tag v-for="workorderStatus in workorderStatusData" :key="workorderStatus.id" class="ml-2" closable
                        :hit="true" :disable-transitions="false" @close="deleteWorkorderStatus(workorderStatus.id)">
                        {{ workorderStatus.name }}
                    </el-tag>

                    <el-input v-if="inputWorkorderStatusVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20"
                        size="small" @blur="createWorkorderStatus(inputValue)" />

                    <el-button v-else class="button-new-tag ml-1" size="small" @click="showWorkorderStatusInput">+
                        添加</el-button>
                </div>
            </el-collapse-item>

            <el-collapse-item name="manager">
                <template #title>
                    <el-icon>
                        <Avatar />
                    </el-icon>
                    <span>管理员数据类型</span>
                </template>
                <h4>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;管理员角色</h4>
                <div class="tag-wrapper">
                    <el-tag v-for="managerRole in managerRoleData" :key="managerRole.id" class="ml-2" closable :hit="true"
                        :disable-transitions="false" @close="deleteManagerRole(managerRole.id)">
                        {{ managerRole.name }}
                    </el-tag>

                    <el-input v-if="inputManagerRoleVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20"
                        size="small" @blur="createManagerRole(inputValue)" />

                    <el-button v-else class="button-new-tag ml-1" size="small" @click="showManagerRoleInput">+
                        添加</el-button>
                </div>
            </el-collapse-item>

            <el-collapse-item name="employee">
                <template #title>
                    <el-icon>
                        <UserFilled />
                    </el-icon>
                    <span>员工数据类型</span>
                </template>

                <h4>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;员工角色</h4>
                <div class="tag-wrapper">
                    <el-tag v-for="employeeRole in employeeRoleData" :key="employeeRole.id" class="ml-2" closable
                        :hit="true" :disable-transitions="false" @close="deleteEmployeeRole(employeeRole.id)">
                        {{ employeeRole.name }}
                    </el-tag>

                    <el-input v-if="inputEmpRoleVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20" size="small"
                        @blur="createEmployeeRole(inputValue)" />

                    <el-button v-else class="button-new-tag ml-1" size="small" @click="showEmpRoleInput">+ 添加</el-button>
                </div>
            </el-collapse-item>
        </el-collapse>
    </div>
</template>
  
<script lang="ts" setup>
import { nextTick, ref } from 'vue'
import { ElInput, ElMessage } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
const router = useRouter();

import { dataTypeGetService, dataTypePostService, dataTypeDeleteService } from "../../../api/other.js";

const activeName = ref("house") //默认激活的抽屉名称

const inputValue = ref('')  // 输入框的输入值

// 输入框可见标志
const inputEmpRoleVisible = ref(false)
const inputHouseTypeVisible = ref(false)
const inputHouseStatusVisible = ref(false)
const inputManagerRoleVisible = ref(false)
const inputWorkorderCategoryVisible = ref(false)
const inputWorkorderStatusVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()// 输入框ref响应式对象

// 抽取显示输入框方法
const showInput = (inputVisible) => {
    inputVisible.value = true
    nextTick(() => { InputRef.value!.input!.focus() })
}
// 代理点击显示输入框方法（为何代理，原因见下方代理请求）
const showEmpRoleInput = () => showInput(inputEmpRoleVisible)
const showHouseTypeInput = () => showInput(inputHouseTypeVisible)
const showHouseStatusInput = () => showInput(inputHouseStatusVisible)
const showManagerRoleInput = () => showInput(inputManagerRoleVisible)
const showWorkorderCategoryInput = () => showInput(inputWorkorderCategoryVisible)
const showWorkorderStatusInput = () => showInput(inputWorkorderStatusVisible)

// 各数据列表的响应式对象
const employeeRoleData = ref([{ id: '', name: '' }])
const houseTypeData = ref([{ id: '', name: '' }])
const houseStatusData = ref([{ id: '', name: '' }])
const managerRoleData = ref([{ id: '', name: '' }])
const workorderCategoryData = ref([{ id: '', name: '' }])
const workorderStatusData = ref([{ id: '', name: '' }])

// 封装get请求
const getData = async function (requestUrl, resultData) {
    try {
        let result = { "code": null, "msg": '', "data": null }
        result = await dataTypeGetService(requestUrl);
        if (result.code == 200) {
            resultData.value = result.data;
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
        else {
            ElMessage.error(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (dataTypeGet)')
    }
}
// 封装delete请求
const deleteData = async function (requestUrl, id, resultData) {
    if (confirm('确定要删除吗？[id:' + id + ']')) {
        try {
            let result = { "code": null, "msg": '', "data": null }
            result = await dataTypeDeleteService(requestUrl, id);
            if (result.code == 200) {
                ElMessage.success(result.msg);
                getData(requestUrl, resultData)
            } else if (result.code == 401) {
                ElMessage.error(result.msg)
                router.push({ path: '/login' });
            } else {
                ElMessage.error(result.msg)
            }
        } catch (error) {
            ElMessage.error('系统异常 (dataTypeDelete)')
        }
    }
}
// 封装post请求
const postData = async function (requestUrl, fieldName, inputName, resultData, inputVisible) {
    try {
        let result = { "code": null, "msg": '', "data": null }
        result = await dataTypePostService(requestUrl, fieldName, inputName);
        if (result.code == 200) {
            ElMessage.success(result.msg);
            getData(requestUrl, resultData)
        } else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        } else {
            ElMessage.error(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (dataTypePost)')
    } finally {
        inputVisible.value = false
        inputValue.value = ''
    }

}

/**
 * 问题说明：
 * 响应式数据更新的对象应该是一个refImpl对象
 * 但从<template>中传过来的对象是个普通对象，做不到响应式数据，故出此下策代理请求
 * 要注意此代理使得代码紧耦合，不利于维护
 */
// 代理delete请求
const deleteEmployeeRole = function (id) { deleteData('/employee/role', id, employeeRoleData) }
const deleteHouseType = function (id) { deleteData('/house/type', id, houseTypeData) }
const deleteHouseStatus = function (id) { deleteData('/house/status', id, houseStatusData) }
const deleteManagerRole = function (id) { deleteData('/manager/role', id, managerRoleData) }
const deleteWorkorderCategory = function (id) { deleteData('/workorder/category', id, workorderCategoryData) }
const deleteWorkorderStatus = function (id) { deleteData('/workorder/status', id, workorderStatusData) }
// 代理post请求
const createEmployeeRole = function (inputName: string) { postData('/employee/role', 'roleName', inputName, employeeRoleData, inputEmpRoleVisible) }
const createHouseType = function (inputName: string) { postData('/house/type', 'typeName', inputName, houseTypeData, inputHouseTypeVisible) }
const createHouseStatus = function (inputName: string) { postData('/house/status', 'statusName', inputName, houseStatusData, inputHouseStatusVisible) }
const createManagerRole = function (inputName: string) { postData('/manager/role', 'roleName', inputName, managerRoleData, inputManagerRoleVisible) }
const createWorkorderCategory = function (inputName: string) { postData('/workorder/category', 'categoryName', inputName, workorderCategoryData, inputWorkorderCategoryVisible) }
const createWorkorderStatus = function (inputName: string) { postData('/workorder/status', 'statusName', inputName, workorderStatusData, inputWorkorderStatusVisible) }

// 激活哪个抽屉，就获取哪部分数据
const getInitData = function (activeName) {
    if (activeName == "house") {
        getHouseData()
    } else if (activeName == "workorder") {
        getWorkorderData()
    } else if (activeName == "manager") {
        getManagerData()
    } else if (activeName == "employee") {
        getEmployeeData()
    }
}


const getHouseData = function () {
    getData('/house/type', houseTypeData)
    getData('/house/status', houseStatusData)
}
const getWorkorderData = function () {
    getData('/workorder/category', workorderCategoryData)
    getData('/workorder/status', workorderStatusData)
}
const getManagerData = function () {
    getData('/manager/role', managerRoleData)
}
const getEmployeeData = function () {
    getData('/employee/role', employeeRoleData)
}

getHouseData()// 默认展示数据

</script>

<style>
.button-new-tag {
    margin-left: 10px;
}

.el-tag+.el-tag {
    margin-left: 10px;
}

.el-collapse .el-collapse-item__header {
    font-size: 16px;
    font-weight: bold;
}

</style>
  